package routers

import (
	"encoding/json"
	"net/http"
	"strconv"
	"strings"
	"time"

	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/entity"

	//	log "github.com/sirupsen/logrus"
	jwt "github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
)

//对公客户认定
func ClientCompDiviRouter(c echo.Context) error {
	//获取操作人
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	userid := strconv.Itoa(claims.UserID)
	var cuids []int
	jsonStr := c.FormValue("Cuids")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "Cuids不能为空！")
	}
	err := json.Unmarshal([]byte(jsonStr), &cuids)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(cuids); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "Cuids不能为空数组！")
	}
	jsonStr = c.FormValue("DataSource")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空！")
	}
	var dataSource []entity.TCompClieDivi
	err = json.Unmarshal([]byte(jsonStr), &dataSource)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(dataSource); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空数组！")
	}
	dsdt := dataSource[0].DSDT
	//查询
	var updateList []entity.TCompClieDivi
	tx := base.DB.Begin()
	err = base.DB.Where("CUID in (?) and ISWO = 0 and (WODT is null or WODT > ?)", cuids, dsdt).Find(&updateList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//终止现有认定
	for _, upateData := range updateList {
		upateData.WODT = &dsdt
		upateData.WOEM = &userid
		if upateData.DSDT.Unix() > dsdt.Unix() {
			upateData.ISWO = true
		}
		err = tx.Model(&(entity.TCompClieDivi{})).Save(&upateData).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	//新增认定
	for _, cuid := range cuids {
		for _, data := range dataSource {
			newData := entity.TCompClieDivi{
				CUID: cuid,
				EMID: data.EMID,
				DSVL: data.DSVL,
				DSDT: data.DSDT,
				DSTY: 1,
				DSEM: userid,
				ISWO: false,
			}
			err = tx.Create(&newData).Error
			if err != nil {
				tx.Rollback()
				return echo.NewHTTPError(http.StatusBadRequest, err.Error())
			}
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//对私客户认定
func ClientIndiDiviRouter(c echo.Context) error {
	//获取操作人
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	userid := strconv.Itoa(claims.UserID)
	var cuids []int
	jsonStr := c.FormValue("Cuids")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "Cuids不能为空！")
	}
	err := json.Unmarshal([]byte(jsonStr), &cuids)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(cuids); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "Cuids不能为空数组！")
	}
	jsonStr = c.FormValue("DataSource")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空！")
	}
	var dataSource []entity.TIndiClieDiviFh
	err = json.Unmarshal([]byte(jsonStr), &dataSource)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(dataSource); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空数组！")
	}
	dsdt := dataSource[0].DSDT
	//查询
	var updateList []entity.TIndiClieDiviFh
	tx := base.DB.Begin()
	err = base.DB.Where("CUID in (?) and ISWO = 0 and (WODT is null or WODT > ?)", cuids, dsdt).Find(&updateList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//终止现有认定
	for _, upateData := range updateList {
		upateData.WODT = &dsdt
		upateData.WOEM = &userid
		if upateData.DSDT.Unix() > dsdt.Unix() {
			upateData.ISWO = true
		}
		err = tx.Model(&(entity.TIndiClieDiviFh{})).Save(&upateData).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	//新增认定
	for _, cuid := range cuids {
		for _, data := range dataSource {
			newData := entity.TIndiClieDiviFh{
				CUID: cuid,
				EMID: data.EMID,
				DSVL: data.DSVL,
				DSDT: data.DSDT,
				DSTY: 1,
				DSEM: userid,
				ISWO: false,
			}
			err = tx.Create(&newData).Error
			if err != nil {
				tx.Rollback()
				return echo.NewHTTPError(http.StatusBadRequest, err.Error())
			}
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

func ClientMinDiviRouter(c echo.Context) error {
	//获取操作人
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	userid := strconv.Itoa(claims.UserID)
	jlid, err := strconv.Atoi(c.FormValue("Jlid"))
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "JLID转换失败！")
	}
	// khlx, err := strconv.Atoi(c.FormValue("Khlx"))
	// if err != nil {
	// 	return echo.NewHTTPError(http.StatusBadRequest, "JLID转换失败！")
	// }
	jsonStr := c.FormValue("DataSource")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空！")
	}
	var dataSource []entity.CM_BIZ_FEE_SUM_M_DIVI
	err = json.Unmarshal([]byte(jsonStr), &dataSource)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(dataSource); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空数组！")
	}
	tx := base.DB.Begin()
	// if khlx == 1 {
	// 	err = tx.Exec("DELETE FROM T_CM_BIZ_FEE_SUM_M_DIVI WHERE JLID=? AND KHLX=1", jlid).Error
	// 	if err != nil {
	// 		return echo.NewHTTPError(http.StatusBadRequest, "删除认定关系失败！")
	// 	}
	// 	for _, data := range dataSource {
	// 		tx.Exec("INSERT INTO T_CM_BIZ_FEE_SUM_M_DIVI(JLID,EMID,DSVL,DSEM,KHLX) "+
	// 			"VALUES(?,?,?,?,?)", jlid, data.EMID, data.DSVL, userid, 1)
	// 	}
	// } else {
	// 	err = tx.Exec("DELETE FROM T_CM_BIZ_FEE_SUM_M_DIVI WHERE JLID=? AND KHLX=2", jlid).Error
	// 	if err != nil {
	// 		return echo.NewHTTPError(http.StatusBadRequest, "删除认定关系失败！")
	// 	}
	// 	for _, data := range dataSource {
	// 		tx.Exec("INSERT INTO T_CM_BIZ_FEE_SUM_M_DIVI(JLID,EMID,DSVL,DSEM,KHLX) "+
	// 			"VALUES(?,?,?,?,?)", jlid, data.EMID, data.DSVL, userid, 2)
	// 	}
	// }
	err = tx.Exec("DELETE FROM T_CM_BIZ_FEE_SUM_M_DIVI WHERE JLID=? AND KHLX in(1,3)", jlid).Error
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "删除认定关系失败！")
	}
	for _, data := range dataSource {
		tx.Exec("INSERT INTO T_CM_BIZ_FEE_SUM_M_DIVI(JLID,EMID,DSVL,DSEM,KHLX,ISWH) "+
			"VALUES(?,?,?,?,?,?)", jlid, data.EMID, data.DSVL, userid, 1, 1)
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//中间业务认定
// func ClientMinDiviRouter(c echo.Context) error {
// 	//获取操作人
// 	user := c.Get("user").(*jwt.Token)
// 	claims := user.Claims.(*UserLoginClaims)
// 	userid := strconv.Itoa(claims.UserID)
// 	var acids []int
// 	jsonStr := c.FormValue("Acids")
// 	if jsonStr == "" {
// 		return echo.NewHTTPError(http.StatusBadRequest, "Acids不能为空！")
// 	}
// 	err := json.Unmarshal([]byte(jsonStr), &acids)
// 	if err != nil {
// 		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
// 	}
// 	if l := len(acids); l == 0 {
// 		return echo.NewHTTPError(http.StatusBadRequest, "Acids不能为空数组！")
// 	}
// 	jsonStr = c.FormValue("DataSource")
// 	if jsonStr == "" {
// 		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空！")
// 	}
// 	var dataSource []entity.MinDivi
// 	err = json.Unmarshal([]byte(jsonStr), &dataSource)
// 	if err != nil {
// 		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
// 	}
// 	if l := len(dataSource); l == 0 {
// 		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空数组！")
// 	}
// 	//查询
// 	var updateList []entity.MinDivi
// 	tx := base.DB.Begin()
// 	err = base.DB.Where("ACID in (?) and ISWO = 0", acids).Find(&updateList).Error
// 	if err != nil {
// 		tx.Rollback()
// 		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
// 	}
// 	//终止现有认定
// 	for _, upateData := range updateList {
// 		upateData.WOEM = &userid
// 		upateData.ISWO = true
// 		err = tx.Model(&(entity.MinDivi{})).Save(&upateData).Error
// 		if err != nil {
// 			tx.Rollback()
// 			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
// 		}
// 	}
// 	//新增认定
// 	for _, acid := range acids {
// 		for _, data := range dataSource {
// 			newData := entity.MinDivi{
// 				ACID: acid,
// 				EMID: data.EMID,
// 				DSVL: data.DSVL,
// 				DSTY: 0,
// 				DSEM: userid,
// 				ISWO: false,
// 			}
// 			err = tx.Create(&newData).Error
// 			if err != nil {
// 				tx.Rollback()
// 				return echo.NewHTTPError(http.StatusBadRequest, err.Error())
// 			}
// 		}
// 	}
// 	tx.Commit()
// 	return c.JSON(http.StatusOK, "OK")
// }

//个人理财认定
func ClientFanaDiviRouter(c echo.Context) error {
	//获取操作人
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	userid := strconv.Itoa(claims.UserID)
	var acids []int
	jsonStr := c.FormValue("Acids")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "Acids不能为空！")
	}
	err := json.Unmarshal([]byte(jsonStr), &acids)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(acids); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "Acids不能为空数组！")
	}
	jsonStr = c.FormValue("DataSource")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空！")
	}
	var dataSource []entity.IndiFanaDivi
	err = json.Unmarshal([]byte(jsonStr), &dataSource)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(dataSource); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空数组！")
	}
	dsdt := dataSource[0].DSDT
	//查询
	var updateList []entity.IndiFanaDivi
	tx := base.DB.Begin()
	var backdate string
	// rows, err := tx.Raw("SELECT dbo.DBO.GetFlowBackDate()").Rows()

	rows, err := tx.Raw("SELECT dbo.GetBackDATEorDSDT(?)", dsdt).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if rows.Next() {
		rows.Scan(&backdate)
	}
	if backdate == "NO" {
		tx.Rollback()
		return c.JSON(http.StatusOK, "分户日期不能小于最早可追溯日期")
	}
	err = base.DB.Where("ACID in (?) and ISWO = 0 and (WODT is null or WODT > ?)", acids, dsdt).Find(&updateList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//终止现有认定
	for _, upateData := range updateList {
		upateData.WODT = &dsdt
		upateData.WOEM = &userid
		if upateData.DSDT.Unix() > dsdt.Unix() {
			upateData.ISWO = true
		}
		err = tx.Model(&(entity.IndiFanaDivi{})).Save(&upateData).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	//新增认定
	for _, acid := range acids {
		for _, data := range dataSource {
			newData := entity.IndiFanaDivi{
				ACID: acid,
				EMID: data.EMID,
				DSVL: data.DSVL,
				DSDT: data.DSDT,
				DSTY: 1,
				DSEM: userid,
				ISWO: false,
			}
			err = tx.Create(&newData).Error
			if err != nil {
				tx.Rollback()
				return echo.NewHTTPError(http.StatusBadRequest, err.Error())
			}
		}
	}
	base.DB.Exec("UPDATE T_INDI_FANA SET ISDIVI=? WHERE FAID IN (?)", 1, acids)
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//个人贷款认定
func ClientLoanDiviRouter(c echo.Context) error {
	//获取操作人
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	userid := strconv.Itoa(claims.UserID)
	var acids []int
	jsonStr := c.FormValue("Acids")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "Acids不能为空！")
	}
	err := json.Unmarshal([]byte(jsonStr), &acids)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(acids); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "Acids不能为空数组！")
	}
	jsonStr = c.FormValue("DataSource")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空！")
	}
	var dataSource []entity.IndiLoanDivi
	err = json.Unmarshal([]byte(jsonStr), &dataSource)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(dataSource); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空数组！")
	}
	dsdt := dataSource[0].DSDT
	//查询
	var updateList []entity.IndiLoanDivi
	tx := base.DB.Begin()
	var backdate string
	rows, err := tx.Raw("SELECT dbo.GetBackDATEorDSDT(?)", dsdt).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if rows.Next() {
		rows.Scan(&backdate)
	}
	if backdate == "NO" {
		tx.Rollback()
		return c.JSON(http.StatusOK, "分户日期不能小于最早可追溯日期")
	}
	err = base.DB.Where("ACID in (?) and ISWO = 0 and (WODT is null or WODT > ?)", acids, dsdt).Find(&updateList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//终止现有认定
	for _, upateData := range updateList {
		upateData.WODT = &dsdt
		upateData.WOEM = &userid
		if upateData.DSDT.Unix() > dsdt.Unix() {
			upateData.ISWO = true
		}
		err = tx.Model(&(entity.IndiLoanDivi{})).Save(&upateData).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	//新增认定
	for _, acid := range acids {
		for _, data := range dataSource {
			newData := entity.IndiLoanDivi{
				ACID: acid,
				EMID: data.EMID,
				DSVL: data.DSVL,
				DSDT: data.DSDT,
				DSTY: 1,
				DSEM: userid,
				ISWO: false,
			}
			err = tx.Create(&newData).Error
			if err != nil {
				tx.Rollback()
				return echo.NewHTTPError(http.StatusBadRequest, err.Error())
			}
		}
	}
	base.DB.Exec("UPDATE T_INDI_LOAN SET ISDIVI=? WHERE ID IN (?)", 1, acids)
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//业绩转移
func UserDiviChange(c echo.Context) error {
	//获取操作人
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	userid := strconv.Itoa(claims.UserID)
	if userid == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "登陆已超时，请重新登陆")
	}
	jsonStr := c.FormValue("DataSource")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空！")
	}
	var dataSource []entity.TUserDiviChange
	err := json.Unmarshal([]byte(jsonStr), &dataSource)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	zcyj := dataSource[0].ZCYJ
	zcdt := dataSource[0].ZCDT
	emid := dataSource[0].EMID
	tx := base.DB.Begin()
	var backdate string
	rows, err := tx.Raw("SELECT dbo.GetBackDATEorDSDT(?)", zcdt).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if rows.Next() {
		rows.Scan(&backdate)
	}
	if backdate == "NO" {
		tx.Rollback()
		return c.JSON(http.StatusOK, "业绩转移日期不能小于最早可追溯日期")
	}
	//验证是否存在虚拟户
	var count int
	rows, err = tx.Raw("SELECT COUNT(*) FROM T_SysUser WHERE ID IN (?,?,?,?,?,?) AND LEFT(RIGHT(SysUserID,9),1)=':'", dataSource[0].EMID, dataSource[0].EMID1, dataSource[0].EMID2, dataSource[0].EMID3, dataSource[0].EMID4, dataSource[0].EMID5).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if rows.Next() {
		rows.Scan(&count)
	}
	if count > 0 {
		tx.Rollback()
		return c.JSON(http.StatusOK, "转入或转出员工为虚拟员工，不支持业绩批量调整！请重新选择")
	}

	newDiviChange := entity.TUserDiviChange{
		EMID:  dataSource[0].EMID,
		ZCDT:  dataSource[0].ZCDT,
		ZCYJ:  dataSource[0].ZCYJ,
		EMID1: dataSource[0].EMID1,
		DSVL1: dataSource[0].DSVL1,
		EMID2: dataSource[0].EMID2,
		DSVL2: dataSource[0].DSVL2,
		EMID3: dataSource[0].EMID3,
		DSVL3: dataSource[0].DSVL3,
		EMID4: dataSource[0].EMID4,
		DSVL4: dataSource[0].DSVL4,
		EMID5: dataSource[0].EMID5,
		DSVL5: dataSource[0].DSVL5,
	}
	err = tx.Create(&newDiviChange).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	//查询对公业绩，并转移
	if index := strings.Contains(zcyj, "1"); index == true {
		var updateCompDiviList []entity.Comp_Divi
		err = tx.Where("EMID =? AND ISWO=0 AND (WODT IS NULL OR WODT>?)", emid, zcdt).Find(&updateCompDiviList).Error
		if err != nil {
			tx.Rollback()
			return err
		}
		for _, compDivi := range updateCompDiviList {
			diviDsvl := compDivi.DSVL
			if compDivi.DSDT.Unix() >= zcdt.Unix() {
				compDivi.ISWO = true
				compDivi.WOEM = &userid
				err = tx.Model(&(entity.Comp_Divi{})).Save(&compDivi).Error
				if err != nil {
					tx.Rollback()
					return err
				}
				if dataSource[0].DSVL1 != 0 {
					newCompDivi := entity.Comp_Divi{
						ACID: compDivi.ACID,
						DSTY: compDivi.DSTY,
						EMID: dataSource[0].EMID1,
						DSVL: compDivi.DSVL * dataSource[0].DSVL1,
						DSDT: compDivi.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL2 != nil {
					newCompDivi := entity.Comp_Divi{
						ACID: compDivi.ACID,
						DSTY: compDivi.DSTY,
						EMID: *dataSource[0].EMID2,
						DSVL: diviDsvl * *dataSource[0].DSVL2,
						DSDT: compDivi.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL3 != nil {
					newCompDivi := entity.Comp_Divi{
						ACID: compDivi.ACID,
						DSTY: compDivi.DSTY,
						EMID: *dataSource[0].EMID3,
						DSVL: compDivi.DSVL * *dataSource[0].DSVL3,
						DSDT: compDivi.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL4 != nil {
					newCompDivi := entity.Comp_Divi{
						ACID: compDivi.ACID,
						DSTY: compDivi.DSTY,
						EMID: *dataSource[0].EMID4,
						DSVL: compDivi.DSVL * *dataSource[0].DSVL4,
						DSDT: compDivi.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL5 != nil {
					newCompDivi := entity.Comp_Divi{
						ACID: compDivi.ACID,
						DSTY: compDivi.DSTY,
						EMID: *dataSource[0].EMID5,
						DSVL: compDivi.DSVL * *dataSource[0].DSVL5,
						DSDT: compDivi.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
			} else {
				compDivi.WODT = zcdt
				compDivi.WOEM = &userid
				err = tx.Model(&(entity.Comp_Divi{})).Save(&compDivi).Error
				if err != nil {
					tx.Rollback()
					return err
				}
				if dataSource[0].DSVL1 != 0 {
					newCompDivi := entity.Comp_Divi{
						ACID: compDivi.ACID,
						DSTY: compDivi.DSTY,
						EMID: dataSource[0].EMID1,
						DSVL: compDivi.DSVL * dataSource[0].DSVL1,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL2 != nil {
					newCompDivi := entity.Comp_Divi{
						ACID: compDivi.ACID,
						DSTY: compDivi.DSTY,
						EMID: *dataSource[0].EMID2,
						DSVL: diviDsvl * *dataSource[0].DSVL2,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL3 != nil {
					newCompDivi := entity.Comp_Divi{
						ACID: compDivi.ACID,
						DSTY: compDivi.DSTY,
						EMID: *dataSource[0].EMID3,
						DSVL: compDivi.DSVL * *dataSource[0].DSVL3,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL4 != nil {
					newCompDivi := entity.Comp_Divi{
						ACID: compDivi.ACID,
						DSTY: compDivi.DSTY,
						EMID: *dataSource[0].EMID4,
						DSVL: compDivi.DSVL * *dataSource[0].DSVL4,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL5 != nil {
					newCompDivi := entity.Comp_Divi{
						ACID: compDivi.ACID,
						DSTY: compDivi.DSTY,
						EMID: *dataSource[0].EMID5,
						DSVL: compDivi.DSVL * *dataSource[0].DSVL5,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
			}
		}
	}
	if index := strings.Contains(zcyj, "2"); index == true {
		var updateIndiDiviList []entity.Indi_Divi
		err = tx.Where("EMID =? AND ISWO=0 AND (WODT IS NULL OR WODT>?)", emid, zcdt).Find(&updateIndiDiviList).Error
		if err != nil {
			tx.Rollback()
			return err
		}
		for _, indiDivi := range updateIndiDiviList {
			diviDsvl := indiDivi.DSVL
			if indiDivi.DSDT.Unix() >= zcdt.Unix() {
				indiDivi.ISWO = true
				indiDivi.WOEM = &userid
				err = tx.Model(&(entity.Indi_Divi{})).Save(&indiDivi).Error
				if err != nil {
					tx.Rollback()
					return err
				}
				if dataSource[0].DSVL1 != 0 {
					newIndiData := entity.Indi_Divi{
						ACID: indiDivi.ACID,
						DSTY: indiDivi.DSTY,
						EMID: dataSource[0].EMID1,
						DSVL: indiDivi.DSVL * dataSource[0].DSVL1,
						DSDT: indiDivi.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiData).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL2 != nil {
					newIndiDivi := entity.Indi_Divi{
						ACID: indiDivi.ACID,
						DSTY: indiDivi.DSTY,
						EMID: *dataSource[0].EMID2,
						DSVL: diviDsvl * *dataSource[0].DSVL2,
						DSDT: indiDivi.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL3 != nil {
					newIndiDivi := entity.Indi_Divi{
						ACID: indiDivi.ACID,
						DSTY: indiDivi.DSTY,
						EMID: *dataSource[0].EMID3,
						DSVL: diviDsvl * *dataSource[0].DSVL3,
						DSDT: indiDivi.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL4 != nil {
					newIndiDivi := entity.Indi_Divi{
						ACID: indiDivi.ACID,
						DSTY: indiDivi.DSTY,
						EMID: *dataSource[0].EMID4,
						DSVL: diviDsvl * *dataSource[0].DSVL4,
						DSDT: indiDivi.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL5 != nil {
					newIndiDivi := entity.Indi_Divi{
						ACID: indiDivi.ACID,
						DSTY: indiDivi.DSTY,
						EMID: *dataSource[0].EMID5,
						DSVL: diviDsvl * *dataSource[0].DSVL5,
						DSDT: indiDivi.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
			} else {
				indiDivi.WODT = zcdt
				indiDivi.WOEM = &userid
				err = tx.Model(&(entity.Indi_Divi{})).Save(&indiDivi).Error
				if err != nil {
					tx.Rollback()
					return err
				}
				if dataSource[0].DSVL1 != 0 {
					newIndiDivi := entity.Indi_Divi{
						ACID: indiDivi.ACID,
						DSTY: indiDivi.DSTY,
						EMID: dataSource[0].EMID1,
						DSVL: indiDivi.DSVL * dataSource[0].DSVL1,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL2 != nil {
					newIndiDivi := entity.Indi_Divi{
						ACID: indiDivi.ACID,
						DSTY: indiDivi.DSTY,
						EMID: *dataSource[0].EMID2,
						DSVL: indiDivi.DSVL * *dataSource[0].DSVL2,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL3 != nil {
					newIndiDivi := entity.Indi_Divi{
						ACID: indiDivi.ACID,
						DSTY: indiDivi.DSTY,
						EMID: *dataSource[0].EMID3,
						DSVL: indiDivi.DSVL * *dataSource[0].DSVL3,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL4 != nil {
					newIndiDivi := entity.Indi_Divi{
						ACID: indiDivi.ACID,
						DSTY: indiDivi.DSTY,
						EMID: *dataSource[0].EMID4,
						DSVL: indiDivi.DSVL * *dataSource[0].DSVL4,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL5 != nil {
					newIndiDivi := entity.Indi_Divi{
						ACID: indiDivi.ACID,
						DSTY: indiDivi.DSTY,
						EMID: *dataSource[0].EMID5,
						DSVL: indiDivi.DSVL * *dataSource[0].DSVL5,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
			}
		}
	}
	if index := strings.Contains(zcyj, "3"); index == true {
		var updateCompClieList []entity.TCompClieDivi
		err = tx.Where("EMID =? AND ISWO=0 AND (WODT IS NULL OR WODT>?)", emid, zcdt).Find(&updateCompClieList).Error
		if err != nil {
			tx.Rollback()
			return err
		}
		for _, compClie := range updateCompClieList {
			diviDsvl := compClie.DSVL
			if compClie.DSDT.Unix() >= zcdt.Unix() {
				compClie.ISWO = true
				compClie.WOEM = &userid
				err = tx.Model(&(entity.TCompClieDivi{})).Save(&compClie).Error
				if err != nil {
					tx.Rollback()
					return err
				}
				if dataSource[0].DSVL1 != 0 {
					newCompDivi := entity.TCompClieDivi{
						CUID: compClie.CUID,
						DSTY: compClie.DSTY,
						EMID: dataSource[0].EMID1,
						DSVL: diviDsvl * dataSource[0].DSVL1,
						DSDT: compClie.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL2 != nil {
					newCompDivi := entity.TCompClieDivi{
						CUID: compClie.CUID,
						DSTY: compClie.DSTY,
						EMID: *dataSource[0].EMID2,
						DSVL: diviDsvl * *dataSource[0].DSVL2,
						DSDT: compClie.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL3 != nil {
					newCompDivi := entity.TCompClieDivi{
						CUID: compClie.CUID,
						DSTY: compClie.DSTY,
						EMID: *dataSource[0].EMID3,
						DSVL: diviDsvl * *dataSource[0].DSVL3,
						DSDT: compClie.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL4 != nil {
					newCompDivi := entity.TCompClieDivi{
						CUID: compClie.CUID,
						DSTY: compClie.DSTY,
						EMID: *dataSource[0].EMID4,
						DSVL: diviDsvl * *dataSource[0].DSVL4,
						DSDT: compClie.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL5 != nil {
					newCompDivi := entity.TCompClieDivi{
						CUID: compClie.CUID,
						DSTY: compClie.DSTY,
						EMID: *dataSource[0].EMID5,
						DSVL: diviDsvl * *dataSource[0].DSVL5,
						DSDT: compClie.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
			} else {
				compClie.WODT = zcdt
				compClie.WOEM = &userid
				err = tx.Model(&(entity.CompClieDivi{})).Save(&compClie).Error
				if err != nil {
					tx.Rollback()
					return err
				}
				if dataSource[0].DSVL1 != 0 {
					newCompDivi := entity.TCompClieDivi{
						CUID: compClie.CUID,
						EMID: dataSource[0].EMID1,
						DSVL: diviDsvl * dataSource[0].DSVL1,
						DSDT: *zcdt,
						DSTY: compClie.DSTY,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL2 != nil {
					newCompDivi := entity.TCompClieDivi{
						CUID: compClie.CUID,
						DSTY: compClie.DSTY,
						EMID: *dataSource[0].EMID2,
						DSVL: diviDsvl * *dataSource[0].DSVL2,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL3 != nil {
					newCompDivi := entity.TCompClieDivi{
						CUID: compClie.CUID,
						DSTY: compClie.DSTY,
						EMID: *dataSource[0].EMID3,
						DSVL: diviDsvl * *dataSource[0].DSVL3,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL4 != nil {
					newCompDivi := entity.TCompClieDivi{
						CUID: compClie.CUID,
						DSTY: compClie.DSTY,
						EMID: *dataSource[0].EMID4,
						DSVL: diviDsvl * *dataSource[0].DSVL4,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL5 != nil {
					newCompDivi := entity.TCompClieDivi{
						CUID: compClie.CUID,
						DSTY: compClie.DSTY,
						EMID: *dataSource[0].EMID5,
						DSVL: diviDsvl * *dataSource[0].DSVL5,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newCompDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
			}
		}
	}
	if index := strings.Contains(zcyj, "4"); index == true {
		var updateIndiClieList []entity.TIndiClieDiviFh
		err = tx.Where("EMID =? AND ISWO=0 AND (WODT IS NULL OR WODT>?)", emid, zcdt).Find(&updateIndiClieList).Error
		if err != nil {
			tx.Rollback()
			return err
		}
		for _, indiClie := range updateIndiClieList {
			diviDsvl := indiClie.DSVL
			if indiClie.DSDT.Unix() >= zcdt.Unix() {
				indiClie.ISWO = true
				indiClie.WOEM = &userid
				err = tx.Model(&(entity.TIndiClieDiviFh{})).Save(&indiClie).Error
				if err != nil {
					tx.Rollback()
					return err
				}
				if dataSource[0].DSVL1 != 0 {
					newIndiDivi := entity.TIndiClieDiviFh{
						CUID: indiClie.CUID,
						DSTY: indiClie.DSTY,
						EMID: dataSource[0].EMID1,
						DSVL: diviDsvl * dataSource[0].DSVL1,
						DSDT: indiClie.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL2 != nil {
					newIndiDivi := entity.TIndiClieDiviFh{
						CUID: indiClie.CUID,
						DSTY: indiClie.DSTY,
						EMID: *dataSource[0].EMID2,
						DSVL: diviDsvl * *dataSource[0].DSVL2,
						DSDT: indiClie.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL3 != nil {
					newIndiDivi := entity.TIndiClieDiviFh{
						CUID: indiClie.CUID,
						DSTY: indiClie.DSTY,
						EMID: *dataSource[0].EMID3,
						DSVL: diviDsvl * *dataSource[0].DSVL3,
						DSDT: indiClie.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL4 != nil {
					newIndiDivi := entity.TIndiClieDiviFh{
						CUID: indiClie.CUID,
						DSTY: indiClie.DSTY,
						EMID: *dataSource[0].EMID4,
						DSVL: diviDsvl * *dataSource[0].DSVL4,
						DSDT: indiClie.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL5 != nil {
					newIndiDivi := entity.TIndiClieDiviFh{
						CUID: indiClie.CUID,
						DSTY: indiClie.DSTY,
						EMID: *dataSource[0].EMID5,
						DSVL: diviDsvl * *dataSource[0].DSVL5,
						DSDT: indiClie.DSDT,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
			} else {
				indiClie.WODT = zcdt
				indiClie.WOEM = &userid
				err = tx.Model(&(entity.TIndiClieDiviFh{})).Save(&indiClie).Error
				if err != nil {
					tx.Rollback()
					return err
				}
				if dataSource[0].DSVL1 != 0 {
					newIndiDivi := entity.TIndiClieDiviFh{
						CUID: indiClie.CUID,
						DSTY: indiClie.DSTY,
						EMID: dataSource[0].EMID1,
						DSVL: diviDsvl * dataSource[0].DSVL1,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL2 != nil {
					newIndiDivi := entity.TIndiClieDiviFh{
						CUID: indiClie.CUID,
						DSTY: indiClie.DSTY,
						EMID: *dataSource[0].EMID2,
						DSVL: diviDsvl * *dataSource[0].DSVL2,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL3 != nil {
					newIndiDivi := entity.TIndiClieDiviFh{
						CUID: indiClie.CUID,
						DSTY: indiClie.DSTY,
						EMID: *dataSource[0].EMID3,
						DSVL: diviDsvl * *dataSource[0].DSVL3,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL4 != nil {
					newIndiDivi := entity.TIndiClieDiviFh{
						CUID: indiClie.CUID,
						DSTY: indiClie.DSTY,
						EMID: *dataSource[0].EMID4,
						DSVL: diviDsvl * *dataSource[0].DSVL4,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
				if dataSource[0].DSVL5 != nil {
					newIndiDivi := entity.TIndiClieDiviFh{
						CUID: indiClie.CUID,
						DSTY: indiClie.DSTY,
						EMID: *dataSource[0].EMID5,
						DSVL: diviDsvl * *dataSource[0].DSVL5,
						DSDT: *zcdt,
						DSEM: userid,
						ISWO: false,
					}
					err = tx.Create(&newIndiDivi).Error
					if err != nil {
						tx.Rollback()
						return err
					}
				}
			}
		}
	}
	if index := strings.Contains(zcyj, "5"); index == true {
		var updateMinList []entity.MinDivi
		err = tx.Where("EMID =? AND ISWO=0", emid, zcdt).Find(&updateMinList).Error
		if err != nil {
			tx.Rollback()
			return err
		}
		for _, minDivi := range updateMinList {
			diviDsvl := minDivi.DSVL
			minDivi.ISWO = true
			minDivi.WOEM = &userid
			err = tx.Model(&(entity.MinDivi{})).Save(&minDivi).Error
			if err != nil {
				tx.Rollback()
				return err
			}
			if dataSource[0].DSVL1 != 0 {
				newMinData := entity.MinDivi{
					ACID: minDivi.ACID,
					DSTY: minDivi.DSTY,
					EMID: dataSource[0].EMID1,
					DSVL: minDivi.DSVL * dataSource[0].DSVL1,
					DSEM: userid,
					ISWO: false,
				}
				err = tx.Create(&newMinData).Error
				if err != nil {
					tx.Rollback()
					return err
				}
			}
			if dataSource[0].DSVL2 != nil {
				newMinDivi := entity.MinDivi{
					ACID: minDivi.ACID,
					DSTY: minDivi.DSTY,
					EMID: *dataSource[0].EMID2,
					DSVL: diviDsvl * *dataSource[0].DSVL2,
					DSEM: userid,
					ISWO: false,
				}
				err = tx.Create(&newMinDivi).Error
				if err != nil {
					tx.Rollback()
					return err
				}
			}
			if dataSource[0].DSVL3 != nil {
				newMinDivi := entity.MinDivi{
					ACID: minDivi.ACID,
					DSTY: minDivi.DSTY,
					EMID: *dataSource[0].EMID3,
					DSVL: diviDsvl * *dataSource[0].DSVL3,
					DSEM: userid,
					ISWO: false,
				}
				err = tx.Create(&newMinDivi).Error
				if err != nil {
					tx.Rollback()
					return err
				}
			}
			if dataSource[0].DSVL4 != nil {
				newMinDivi := entity.MinDivi{
					ACID: minDivi.ACID,
					DSTY: minDivi.DSTY,
					EMID: *dataSource[0].EMID4,
					DSVL: diviDsvl * *dataSource[0].DSVL4,
					DSEM: userid,
					ISWO: false,
				}
				err = tx.Create(&newMinDivi).Error
				if err != nil {
					tx.Rollback()
					return err
				}
			}
			if dataSource[0].DSVL5 != nil {
				newMinDivi := entity.MinDivi{
					ACID: minDivi.ACID,
					DSTY: minDivi.DSTY,
					EMID: *dataSource[0].EMID5,
					DSVL: diviDsvl * *dataSource[0].DSVL5,
					DSEM: userid,
					ISWO: false,
				}
				err = tx.Create(&newMinDivi).Error
				if err != nil {
					tx.Rollback()
					return err
				}
			}
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//业绩认定审批保存并提交对公
func ClientCompWorkFlowRouter(c echo.Context) error {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	//是否提交ISTJ
	var ISTJ string
	jsonISTJ := c.FormValue("ISTJ")
	err := json.Unmarshal([]byte(jsonISTJ), &ISTJ)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	jsonStr := c.FormValue("DataSource")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空！")
	}
	var dataSource []entity.TCompDiviWorkflow
	err = json.Unmarshal([]byte(jsonStr), &dataSource)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	encd := dataSource[0].ENCD
	cunm := dataSource[0].NAME
	utid := dataSource[0].UTID
	//查询组织机构代码与企业名称是否相符
	var selectList []entity.TCompClie
	tx := base.DB.Begin()
	//验证分户日期是否小于最早追溯日期
	var backdate string
	rows, err := tx.Raw("SELECT dbo.GetBackDATEorDSDT(?)", dataSource[0].DSDT).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if rows.Next() {
		rows.Scan(&backdate)
	}
	if backdate == "NO" {
		tx.Rollback()
		return c.JSON(http.StatusOK, "分户日期不能小于最早可追溯日期")
	}
	//查询组织机构代码与企业名称是否相符
	if err = base.DB.Where("ENCD=? AND CUNM= ?", encd, cunm).Find(&selectList).Error; err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(selectList); l == 0 {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, "组织机构代码与企业名称不相符，保存失败！")
	}
	//验证是否为新客户
	sqlDivi := "SELECT * FROM T_COMP_ACCO_DIVI A INNER JOIN T_COMP_ACCO B ON A.ACID=B.ID WHERE B.CUID =?"
	rows, err = base.DB.Raw(sqlDivi, selectList[0].ID).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	for rows.Next() {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, "该企业已存在营销关系，保存失败！")
	}
	//验证该客户认定是否已经通过认定审批
	sqlSel := "select * from T_COMP_DIVI_WORKFLOW A INNER JOIN T_COMP_DIVI_WORKFLOW_STEP B ON A.ID=B.WFID WHERE ENCD= ? AND CUNM=? AND B.STATE<>-1"
	rows, err = base.DB.Raw(sqlSel, encd, cunm).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	for rows.Next() {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, "该企业正在进行认定审批或已审批完成，无法再次发起审批流程，保存失败！")
	}
	var step = 0
	if ISTJ == "Y" {
		step = 1
	}
	//新增
	newData := entity.TCompDiviWorkflow{
		ENCD:  encd,
		NAME:  cunm,
		EMID1: dataSource[0].EMID1,
		DSVL1: dataSource[0].DSVL1,
		EMID2: dataSource[0].EMID2,
		DSVL2: dataSource[0].DSVL2,
		EMID3: dataSource[0].EMID3,
		DSVL3: dataSource[0].DSVL3,
		EMID4: dataSource[0].EMID4,
		DSVL4: dataSource[0].DSVL4,
		EMID5: dataSource[0].EMID5,
		DSVL5: dataSource[0].DSVL5,
		DSDT:  dataSource[0].DSDT,
		STEP:  step,
		SQR:   claims.UserID,
	}
	if err = tx.Create(&newData).Error; err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//查询新增的审批信息的ID
	var workID = newData.ID
	//获取workflow配置
	workflow := base.WFContext.GetWorkFlow("compworkflow")
	//判断是否提交，提交则第一步状态为已完成。否则为正在处理
	var stateStart = 0
	if ISTJ == "Y" {
		stateStart = 1
	}
	//保存审批填写人流程
	newStepData := entity.TCompDiviWorkflowStep{
		WFID:  workID,
		EMID:  claims.UserID,
		STEP:  0,
		STATE: stateStart,
	}
	err = tx.Create(&newStepData).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if ISTJ == "Y" {
		for _, action := range workflow.Actions {
			if action.Step == 0 || action.Execute == "" {
				continue
			}
			var prams []interface{}
			var sql string
			if action.Isinorgan == true {
				sql = "SELECT dbo.GetCompWorkFlow(?,?)"
				prams = make([]interface{}, 2)
				prams[0] = claims.UserID
				prams[1] = utid
			} else {
				sql = "SELECT UserId FROM t_UserRole WHERE RoleId IN (?)"
				prams = make([]interface{}, 1)
				prams[0] = strings.Split(action.Execute, ",")
			}
			rows, err := base.DB.Raw(sql, prams...).Rows()
			if err != nil {
				tx.Rollback()
				return echo.NewHTTPError(http.StatusBadRequest, err.Error())
			}
			var userId int
			for rows.Next() {
				rows.Scan(&userId)
				newStepData = entity.TCompDiviWorkflowStep{
					WFID:  workID,
					EMID:  userId,
					STEP:  action.Step,
					STATE: 0,
				}
				err = tx.Create(&newStepData).Error
				if err != nil {
					tx.Rollback()
					return echo.NewHTTPError(http.StatusBadRequest, err.Error())
				}
			}
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//对公审批提交
func ClientCompSubmitWorkFlowRouter(c echo.Context) error {
	var keys []int
	Key := c.FormValue("KEY")
	if Key == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "请选择需要提交的审批申请")
	}
	err := json.Unmarshal([]byte(Key), &keys)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(keys); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "请选择需要提交的审批申请！")
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	userId := claims.UserID
	//查询客户表
	var updateFlowList []entity.TCompDiviWorkflow
	tx := base.DB.Begin()
	err = base.DB.Where("ID IN (?)", keys).Find(&updateFlowList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//获取workflow配置
	workflow := base.WFContext.GetWorkFlow("indiworkflow")
	//获取当前提交人节点
	var step int
	var utid int
	var workID int
	var SpStep int
	//修改客户表审批状态
	for _, updateFlowData := range updateFlowList {
		SpStep = updateFlowData.STEP + 1
		step = updateFlowData.STEP
		utid = updateFlowData.UTID
		workID = updateFlowData.ID
		updateFlowData.STEP = updateFlowData.STEP + 1
		err = tx.Model(&(entity.TCompDiviWorkflow{})).Save(&updateFlowData).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	//查询审批表
	var updateStepList entity.TCompDiviWorkflowStep
	err = base.DB.Where("WFID IN (?) AND EMID =?", keys, userId).Find(&updateStepList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//修改审批表审批状态
	updateStepList.STATE = 1
	err = tx.Model(&(entity.TCompDiviWorkflowStep{})).Save(&updateStepList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	} //判断审批节点为创建时，新增复核节点
	if step == 0 {
		for _, action := range workflow.Actions {
			if action.Step == 0 || action.Execute == "" {
				continue
			}
			var prams []interface{}
			var sql string
			if action.Isinorgan == true {
				sql = "SELECT dbo.GetCompWorkFlow(?,?)"
				prams = make([]interface{}, 2)
				prams[0] = userId
				prams[1] = utid
			} else {
				sql = "SELECT UserId FROM t_UserRole WHERE RoleId IN (?)"
				prams = make([]interface{}, 1)
				prams[0] = strings.Split(action.Execute, ",")
			}
			rows, err := base.DB.Raw(sql, prams...).Rows()
			if err != nil {
				tx.Rollback()
				return echo.NewHTTPError(http.StatusBadRequest, err.Error())
			}
			var AnuserId int
			for rows.Next() {
				rows.Scan(&AnuserId)
				newStepData := entity.TCompDiviWorkflowStep{
					WFID:  workID,
					EMID:  AnuserId,
					STEP:  action.Step,
					STATE: 0,
				}
				err = tx.Create(&newStepData).Error
				if err != nil {
					tx.Rollback()
					return echo.NewHTTPError(http.StatusBadRequest, err.Error())
				}
			}
		}
	}
	if SpStep == 2 {
		err = tx.Exec("EXEC UP_WorkFlow_Divi_Comp ?", keys[0]).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//对公审批退回
func ClientCompRollWorkFlowRouter(c echo.Context) error {
	var keys []int
	Key := c.FormValue("KEY")
	if Key == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "请选择需要退回的审批申请")
	}
	err := json.Unmarshal([]byte(Key), &keys)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(keys); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "请选择需要退回的审批申请！")
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	userId := claims.UserID
	tx := base.DB.Begin()
	//查询客户表
	var updateFlowList []entity.TCompDiviWorkflow
	err = base.DB.Where("ID IN (?)", keys).Find(&updateFlowList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//修改客户表审批状态
	for _, updateFlowData := range updateFlowList {
		updateFlowData.STEP = -1
		err = tx.Model(&(entity.TCompDiviWorkflow{})).Save(&updateFlowData).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	//查询审批表
	var updateStepList entity.TCompDiviWorkflowStep
	err = base.DB.Where("WFID IN (?) AND EMID =?", keys, userId).Find(&updateStepList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//修改审批表审批状态
	updateStepList.STATE = -1
	err = tx.Model(&(entity.TCompDiviWorkflowStep{})).Save(&updateStepList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//查询审批流程意见
func CompWorkFlowStep(c echo.Context) error {
	wfid := c.FormValue("WFID")
	//查询审批表
	var updateStepList []entity.CompWorkflowStep
	err := base.DB.Where("WFID IN (?)", wfid).Find(&updateStepList).Error
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, updateStepList)
}

//查询对公审批
func TCompWorkFlowStep(c echo.Context) error {
	wfid := c.FormValue("ID")
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	emid := claims.UserID
	//查询审批表
	var updateStepList []entity.CompWorkflow
	err := base.DB.Where("ID IN (?) AND EMID = ?", wfid, emid).Find(&updateStepList).Error
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, updateStepList)
}

//业绩认定审批保存并提交对私
func ClientIndiWorkFlowRouter(c echo.Context) error {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	//是否提交ISTJ
	var ISTJ string
	jsonISTJ := c.FormValue("ISTJ")
	err := json.Unmarshal([]byte(jsonISTJ), &ISTJ)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	jsonStr := c.FormValue("DataSource")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空！")
	}
	var dataSource []entity.TIndiDiviWorkflow
	err = json.Unmarshal([]byte(jsonStr), &dataSource)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	idno := dataSource[0].IDNO
	cunm := dataSource[0].NAME
	utid := dataSource[0].UTID
	//查询客户名称与证件号码是否相符
	var selectList []entity.TIndiClie
	tx := base.DB.Begin()
	//验证分户日期是否小于最早追溯日期
	var backdate string
	rows, err := tx.Raw("SELECT dbo.GetBackDATEorDSDT(?)", dataSource[0].DSDT).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if rows.Next() {
		rows.Scan(&backdate)
	}
	if backdate == "NO" {
		tx.Rollback()
		return c.JSON(http.StatusOK, "分户日期不能小于最早可追溯日期")
	}
	//验证客户信息是否匹配
	if err = base.DB.Where("IDNO=? AND INCN= ?", idno, cunm).Find(&selectList).Error; err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(selectList); l == 0 {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, "客户名称与证件号码不相符，保存失败！")
	}
	//验证是否为新客户
	sqlDivi := "SELECT * FROM T_INDI_ACCO_DIVI A INNER JOIN T_INDI_ACCO B ON A.ACID=B.ID WHERE B.CUID =?"
	rows, err = base.DB.Raw(sqlDivi, selectList[0].NO).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	for rows.Next() {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, "该客户已存在营销关系，保存失败！")
	}
	//验证该客户认定是否已经通过认定审批
	sqlSel := "select * from T_INDI_DIVI_WORKFLOW A INNER JOIN T_INDI_DIVI_WORKFLOW_STEP B ON A.ID=B.WFID WHERE IDNO= ? AND CUNM=? AND B.STATE<>-1 AND A.STEP<>-1"
	rows, err = base.DB.Raw(sqlSel, idno, cunm).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	for rows.Next() {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, "该客户正在进行认定审批或已审批完成，无法再次发起审批流程，保存失败！")
	}
	var step = 0
	if ISTJ == "Y" {
		step = 1
	}
	//新增
	newData := entity.TIndiDiviWorkflow{
		IDNO:  idno,
		NAME:  cunm,
		EMID1: dataSource[0].EMID1,
		DSVL1: dataSource[0].DSVL1,
		EMID2: dataSource[0].EMID2,
		DSVL2: dataSource[0].DSVL2,
		EMID3: dataSource[0].EMID3,
		DSVL3: dataSource[0].DSVL3,
		EMID4: dataSource[0].EMID4,
		DSVL4: dataSource[0].DSVL4,
		EMID5: dataSource[0].EMID5,
		DSVL5: dataSource[0].DSVL5,
		DSDT:  dataSource[0].DSDT,
		STEP:  step,
		SQR:   claims.UserID,
		UTID:  utid,
	}
	if err = tx.Create(&newData).Error; err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//查询新增的审批信息的ID
	var workID = newData.ID
	//获取workflow配置
	workflow := base.WFContext.GetWorkFlow("indiworkflow")
	//判断是否提交，提交则第一步状态为已完成。否则为正在处理
	var stateStart = 0
	if ISTJ == "Y" {
		stateStart = 1
	}
	//保存审批填写人流程
	newStepData := entity.TIndiDiviWorkflowStep{
		WFID:  workID,
		EMID:  claims.UserID,
		STEP:  0,
		STATE: stateStart,
	}
	err = tx.Create(&newStepData).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//保存提交才创建审批节点
	if ISTJ == "Y" {
		for _, action := range workflow.Actions {
			if action.Step == 0 || action.Execute == "" {
				continue
			}
			var prams []interface{}
			var sql string
			if action.Isinorgan == true {
				sql = "SELECT dbo.GetIndiWorkFlow(?,?)"
				prams = make([]interface{}, 2)
				prams[0] = claims.UserID
				prams[1] = utid
			} else {
				sql = "SELECT UserId FROM t_UserRole WHERE RoleId IN (?)"
				prams = make([]interface{}, 1)
				prams[0] = strings.Split(action.Execute, ",")
			}
			rows, err := base.DB.Raw(sql, prams...).Rows()
			if err != nil {
				tx.Rollback()
				return echo.NewHTTPError(http.StatusBadRequest, err.Error())
			}
			var userId int
			for rows.Next() {
				rows.Scan(&userId)
				newStepData = entity.TIndiDiviWorkflowStep{
					WFID:  workID,
					EMID:  userId,
					STEP:  action.Step,
					STATE: 0,
				}
				err = tx.Create(&newStepData).Error
				if err != nil {
					tx.Rollback()
					return echo.NewHTTPError(http.StatusBadRequest, err.Error())
				}
			}
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//审批提交对私
func ClientIndiSubmitWorkFlowRouter(c echo.Context) error {
	var keys []int
	Key := c.FormValue("KEY")
	if Key == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "请选择需要提交的审批申请")
	}
	err := json.Unmarshal([]byte(Key), &keys)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(keys); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "请选择需要提交的审批申请！")
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	userId := claims.UserID
	//查询客户表
	var updateFlowList []entity.TIndiDiviWorkflow
	tx := base.DB.Begin()
	err = base.DB.Where("ID IN (?)", keys).Find(&updateFlowList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//获取workflow配置
	workflow := base.WFContext.GetWorkFlow("indiworkflow")
	//获取当前提交人节点
	var step int
	var utid int
	var workID int
	var SpStep int
	//修改客户表审批节点
	for _, updateFlowData := range updateFlowList {
		SpStep = updateFlowData.STEP + 1
		step = updateFlowData.STEP
		utid = updateFlowData.UTID
		workID = updateFlowData.ID
		updateFlowData.STEP = updateFlowData.STEP + 1
		err = tx.Model(&(entity.TIndiDiviWorkflow{})).Save(&updateFlowData).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	//查询审批表
	var updateStepList entity.TIndiDiviWorkflowStep
	err = base.DB.Where("WFID IN (?) AND EMID =?", keys, userId).Find(&updateStepList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//修改审批表审批状态
	updateStepList.STATE = 1
	err = tx.Model(&(entity.TIndiDiviWorkflowStep{})).Save(&updateStepList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//判断审批节点为创建时，新增复核节点
	if step == 0 {
		for _, action := range workflow.Actions {
			if action.Step == 0 || action.Execute == "" {
				continue
			}
			var prams []interface{}
			var sql string
			if action.Isinorgan == true {
				sql = "SELECT dbo.GetIndiWorkFlow(?,?)"
				prams = make([]interface{}, 2)
				prams[0] = claims.UserID
				prams[1] = utid
			} else {
				sql = "SELECT UserId FROM t_UserRole WHERE RoleId IN (?)"
				prams = make([]interface{}, 1)
				prams[0] = strings.Split(action.Execute, ",")
			}
			rows, err := base.DB.Raw(sql, prams...).Rows()
			if err != nil {
				tx.Rollback()
				return echo.NewHTTPError(http.StatusBadRequest, err.Error())
			}
			var AnuserId int
			for rows.Next() {
				rows.Scan(&AnuserId)
				newStepData := entity.TIndiDiviWorkflowStep{
					WFID:  workID,
					EMID:  AnuserId,
					STEP:  action.Step,
					STATE: 0,
				}
				err = tx.Create(&newStepData).Error
				if err != nil {
					tx.Rollback()
					return echo.NewHTTPError(http.StatusBadRequest, err.Error())
				}
			}
		}
	}
	//判断节点为此条审批完成时，
	if SpStep == 2 {
		err = tx.Exec("EXEC UP_WorkFlow_Divi_Indi ?", keys[0]).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//审批退回对私
func ClientIndiRollWorkFlowRouter(c echo.Context) error {
	var keys []int
	Key := c.FormValue("KEY")
	if Key == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "请选择需要退回的审批申请")
	}
	err := json.Unmarshal([]byte(Key), &keys)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(keys); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "请选择需要退回的审批申请！")
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	userId := claims.UserID
	tx := base.DB.Begin()
	//查询客户表
	var updateFlowList []entity.TIndiDiviWorkflow
	err = base.DB.Where("ID IN (?)", keys).Find(&updateFlowList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//修改客户表审批状态
	for _, updateFlowData := range updateFlowList {
		updateFlowData.STEP = -1
		err = tx.Model(&(entity.TIndiDiviWorkflow{})).Save(&updateFlowData).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	//查询审批表
	var updateStepList entity.TIndiDiviWorkflowStep
	err = base.DB.Where("WFID IN (?) AND EMID =?", keys, userId).Find(&updateStepList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//修改审批表审批状态
	updateStepList.STATE = -1
	err = tx.Model(&(entity.TIndiDiviWorkflowStep{})).Save(&updateStepList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//查询对私审批流程意见
func IndiWorkFlowStep(c echo.Context) error {
	wfid := c.FormValue("WFID")
	//查询审批表
	var updateStepList []entity.IndiWorkflowStep
	err := base.DB.Where("WFID IN (?)", wfid).Find(&updateStepList).Error
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, updateStepList)
}

//查询对私审批
func TIndiWorkFlowStep(c echo.Context) error {
	wfid := c.FormValue("ID")
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	emid := claims.UserID
	//查询审批表
	var updateStepList []entity.IndiWorkflow
	err := base.DB.Where("ID IN (?) AND EMID = ?", wfid, emid).Find(&updateStepList).Error
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, updateStepList)
}

//获取当前登陆用户
func GetLogin(c echo.Context) error {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	return c.JSON(http.StatusOK, claims.UserID)
}

//零售基数调整
func IndiYgjsTz(c echo.Context) error {
	jsonStr := c.FormValue("DataSource")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空！")
	}
	var dataSource []entity.BaseYgjsTz
	err := json.Unmarshal([]byte(jsonStr), &dataSource)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(dataSource); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空数组！")
	}
	var sql string
	sql = "SELECT MAX(JLID) ID FROM T_BASE_YGJS_TZ"
	rows, err := base.DB.Raw(sql).Rows()
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	var MaxId string
	for rows.Next() {
		rows.Scan(&MaxId)
	}
	tx := base.DB.Begin()
	var BaseYgjsTz []entity.BaseYgjsTz
	//删除现有调整
	err = base.DB.Where("LSH=?", dataSource[0].LSH+MaxId).Delete(&BaseYgjsTz).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, "删除现有调整失败！")
	}
	for _, data := range dataSource {
		newData := entity.BaseYgjsTz{
			DTID: data.DTID,
			YWID: data.YWID,
			EMID: data.EMID,
			SDJS: data.SDJS,
			RJJS: data.RJJS,
			LSH:  data.LSH + MaxId,
		}
		err = base.DB.Create(&newData).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//中间业务修改付款户名-对公
func ClientMinXghmDiviRouter(c echo.Context) error {
	jsonStr := c.FormValue("DataSource")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空！")
	}
	var dataSource []entity.MinOperClie
	err := json.Unmarshal([]byte(jsonStr), &dataSource)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(dataSource); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空数组！")
	}
	tx := base.DB.Begin()
	var moid = dataSource[0].MOID
	//删除已存在的付款账户
	var sql string
	sql = "DELETE FROM T_MIN_OPER_CLIE WHERE YWLX=1 AND MOID=?"
	err = tx.Exec(sql, moid).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	var (
		ACID int
		CUNM string
	)
	//查询付款户最早的账户ID
	for _, upateData := range dataSource {
		sql = "SELECT MIN(A.ID) ACID,MIN(CUNM) CUNM FROM T_COMP_ACCO A INNER JOIN T_BASE_ITEM C ON A.ITEM=C.ID INNER JOIN T_CONF_STTP D ON C.STTP=D.TPNO WHERE D.FPNO=1 AND A.CUID=?"
		rows, err := tx.Raw(sql, upateData.CUID).Rows()
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		if rows.Next() {
			rows.Scan(&ACID, &CUNM)
		}
		if CUNM == "" {
			tx.Rollback()
			return c.JSON(http.StatusOK, "户名不存在，请重新选择")
		}
		newData := entity.MinOperClie{
			MOID: upateData.MOID,
			CUID: ACID,
			ZSJE: upateData.ZSJE,
			YWLX: 1,
		}
		err = tx.Create(&newData).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	sql = "SELECT TOP 1 B.CUID,A.CUNM FROM T_COMP_ACCO A INNER JOIN T_MIN_OPER_CLIE B ON A.ID=B.CUID WHERE YWLX=1 AND MOID=? ORDER BY B.ID DESC"
	rows, err := tx.Raw(sql, moid).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if rows.Next() {
		rows.Scan(&ACID, &CUNM)
	}
	sql = "UPDATE T_MIN_OPER SET CUNM=?,ACID=? WHERE ID=?"
	err = tx.Exec(sql, &CUNM, &ACID, moid).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//中间业务修改付款户名-零售
func ClientMinXghmLsDiviRouter(c echo.Context) error {
	jsonStr := c.FormValue("DataSource")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空！")
	}
	var dataSource []entity.MinOperClie
	err := json.Unmarshal([]byte(jsonStr), &dataSource)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(dataSource); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空数组！")
	}
	tx := base.DB.Begin()
	var moid = dataSource[0].MOID
	//删除已存在的付款账户
	var sql string
	sql = "DELETE FROM T_MIN_OPER_CLIE WHERE YWLX=2 AND MOID=?"
	err = tx.Exec(sql, moid).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	var (
		ACID int
		CUNM string
	)
	//查询付款户最早的账户ID
	for _, upateData := range dataSource {
		sql = "SELECT MIN(A.ID) ACID,MIN(CUNM) CUNM FROM T_INDI_ACCO A INNER JOIN T_BASE_ITEM C ON A.ITEM=C.ID INNER JOIN T_CONF_STTP D ON C.STTP=D.TPNO WHERE D.FPNO=3 AND A.CUID=?"
		rows, err := tx.Raw(sql, upateData.CUID).Rows()
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		if rows.Next() {
			rows.Scan(&ACID, &CUNM)
		}
		if CUNM == "" {
			tx.Rollback()
			return c.JSON(http.StatusOK, "户名不存在，请重新选择")
		}
		newData := entity.MinOperClie{
			MOID: upateData.MOID,
			CUID: ACID,
			ZSJE: upateData.ZSJE,
			YWLX: 2,
		}
		err = tx.Create(&newData).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	//查询某笔中间业务的最后一个付款人，并更新中间业务表的CUNM和ACID
	sql = "SELECT TOP 1 B.CUID,A.CUNM FROM T_INDI_ACCO A INNER JOIN T_MIN_OPER_CLIE B ON A.ID=B.CUID WHERE YWLX=2 AND MOID=? ORDER BY B.ID DESC"
	rows, err := tx.Raw(sql, moid).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if rows.Next() {
		rows.Scan(&ACID, &CUNM)
	}
	sql = "UPDATE T_MIN_OPER SET CUNM=?,PCUID=? WHERE ID=?"
	err = tx.Exec(sql, &CUNM, &ACID, moid).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//员工调动信息审批保存
func UserCreateWorkFlowRouter(c echo.Context) error {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	jsonStr := c.FormValue("DataSource")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "DataSource不能为空！")
	}
	var dataSource []entity.UserNewOrgan
	err := json.Unmarshal([]byte(jsonStr), &dataSource)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	EMID := dataSource[0].EMID
	DDDT := dataSource[0].DDDT
	//查询客户名称与证件号码是否相符
	tx := base.DB.Begin() //验证是否存在虚拟户
	var backdate time.Time
	row := tx.Raw("select dbo.GetBackDATE()").Row()
	err = row.Scan(&backdate)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if backdate.After(DDDT) {
		tx.Rollback()
		return c.JSON(http.StatusOK, "调动日期不能超过追溯日期！请重新选择")
	}
	var count int
	rows, err := tx.Raw("SELECT COUNT(*) FROM T_SysUser WHERE ID IN (?) AND LEFT(RIGHT(SysUserID,9),1)=':'", EMID).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if rows.Next() {
		rows.Scan(&count)
	}
	if count > 0 {
		tx.Rollback()
		return c.JSON(http.StatusOK, "调动员工为虚拟员工，不支持业绩批量调整！请重新选择")
	}
	//验证该客户认定是否已经通过认定审批
	sqlSel := "select * from T_SysUser_YGDD A INNER JOIN T_SysUser_YGDD_STEP B ON A.ID=B.ddID WHERE A.EMID= ? AND B.STATE<>-1 AND A.STEP NOT IN (-1,2)"
	rows, err = base.DB.Raw(sqlSel, EMID).Rows()
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	for rows.Next() {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, "该员工调动信息正在进行审批，无法再次发起审批流程，保存失败！")
	}
	//获取原部门
	var updateUser entity.User
	err = base.DB.Where("ID =?", EMID).Find(&updateUser).Error
	if err != nil {
		return err
	}
	//新增
	newData := entity.UserNewOrgan{
		EMID:  EMID,
		OUTID: updateUser.OrganizationID,
		NUTID: dataSource[0].NUTID,
		DDDT:  DDDT,
		STEP:  0,
	}
	if err = tx.Create(&newData).Error; err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//查询新增的审批信息的ID
	var ygddID = newData.ID
	//保存审批填写人流程
	newStepData := entity.UserWorkStep{
		DDID:  ygddID,
		EMID:  claims.UserID,
		STEP:  0,
		STATE: 0,
	}
	err = tx.Create(&newStepData).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//员工调动信息审批提交
func UserSubmitWorkFlowRouter(c echo.Context) error {
	var keys []int
	Key := c.FormValue("KEY")
	if Key == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "请选择需要提交的调动信息申请")
	}
	err := json.Unmarshal([]byte(Key), &keys)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(keys); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "请选择需要提交的调动信息申请！")
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	userId := claims.UserID
	//查询客户表
	var updateFlowList []entity.UserNewOrgan
	tx := base.DB.Begin()
	err = base.DB.Where("ID IN (?)", keys).Find(&updateFlowList).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//获取workflow配置
	workflow := base.WFContext.GetWorkFlow("ygddworkflow")
	//获取当前提交人节点
	var step int
	var workID int
	//修改客户表审批节点
	for _, updateFlowData := range updateFlowList {
		step = updateFlowData.STEP
		workID = updateFlowData.ID
		updateFlowData.STEP = updateFlowData.STEP + 1
		err = tx.Model(&(entity.UserNewOrgan{})).Save(&updateFlowData).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	//更新审批表状态
	err = base.DB.Exec("UPDATE T_SysUser_YGDD_STEP SET STATE=1 WHERE DDID= ? AND EMID=?", keys, userId).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	//判断审批节点为创建时，新增复核节点
	if step == 0 {
		for _, action := range workflow.Actions {
			if action.Step == 0 || action.Execute == "" {
				continue
			}
			var prams []interface{}
			var sql string
			if action.Isinorgan == true {
				sql = "SELECT UserId FROM t_UserRole WHERE RoleId IN (?)"
				prams = make([]interface{}, 1)
				prams[0] = strings.Split(action.Execute, ",")
			} else {
				sql = "SELECT UserId FROM t_UserRole WHERE RoleId = 8"
				prams = make([]interface{}, 1)
				prams[0] = strings.Split(action.Execute, ",")
			}
			rows, err := base.DB.Raw(sql, prams...).Rows()
			if err != nil {
				tx.Rollback()
				return echo.NewHTTPError(http.StatusBadRequest, err.Error())
			}
			var AnuserId int
			for rows.Next() {
				rows.Scan(&AnuserId)
				newStepData := entity.UserWorkStep{
					DDID:  workID,
					EMID:  AnuserId,
					STEP:  action.Step,
					STATE: 0,
				}
				err = tx.Create(&newStepData).Error
				if err != nil {
					tx.Rollback()
					return echo.NewHTTPError(http.StatusBadRequest, err.Error())
				}
			}
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}

//查询员工调动信息表，确定选中的数据信息是否可以提交
func UserStepWorkFlowRouter(c echo.Context) error {
	wfid := c.FormValue("ID")
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	emid := claims.UserID
	//查询审批表
	var updateStepList []entity.UserWorkflow
	err := base.DB.Where("ID IN (?) AND CZRID = ?", wfid, emid).Find(&updateStepList).Error
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, updateStepList)
}

//业绩转移方式选择：业绩部分留下时，查询员工调动信息表，确定选中的员工信息是否导入所有的营销关系
func UserImportDiviSelRouter(c echo.Context) error {
	YGid := c.FormValue("ID")
	//查询审批表
	var updateList entity.UserNewOrgan
	err := base.DB.Where("ID = ?", YGid).Find(&updateList).Error
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, updateList)
}

//保存业绩转移方式，提交流程，更新营销关系
func UserOrganUpdateRouter(c echo.Context) error {
	YGid := c.FormValue("ID")
	var YJBD string
	jsonYJBD := c.FormValue("YJBD")
	err := json.Unmarshal([]byte(jsonYJBD), &YJBD)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	var NEMID string
	jsonEMID := c.FormValue("NEMID")
	err = json.Unmarshal([]byte(jsonEMID), &NEMID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	tx := base.DB.Begin()
	if YJBD == "2" {
		emid, _ := strconv.Atoi(NEMID)
		var count int
		rows, err := tx.Raw("SELECT COUNT(*) FROM T_SysUser WHERE ID IN (?) AND LEFT(RIGHT(SysUserID,9),1)=':'", emid).Rows()
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		if rows.Next() {
			rows.Scan(&count)
		}
		if count > 0 {
			tx.Rollback()
			return c.JSON(http.StatusOK, "业绩保留员工为虚拟员工，不支持业绩批量调整！请重新选择")
		}
		err = tx.Exec("UPDATE T_SysUser_YGDD SET YJBD='2',NEWEMID=? WHERE ID= ? ", emid, YGid).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	} else {
		err = tx.Exec("UPDATE T_SysUser_YGDD SET YJBD=? WHERE ID= ?", &YJBD, YGid).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	//获取当前操作人
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	userId := claims.UserID
	//查询员工部门调动表
	err = tx.Exec("UPDATE T_SysUser_YGDD SET STEP=2 WHERE ID= ?", YGid).Error
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//更新审批表状态
	err = tx.Exec("UPDATE T_SysUser_YGDD_STEP SET STATE=1 WHERE DDID= ? AND EMID=?", YGid, userId).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	//更新处理业绩调整存储过程
	err = tx.Exec("EXEC UP_USER_NEW_ORGAN ?", YGid).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "OK")
}
